import ProLayout from '@ant-design/pro-layout';
import React, {useEffect, useRef, useState} from 'react';
import {connect, history, Link, useIntl} from 'umi';
import {BackTop} from 'antd';
import RightContent from '@/components/GlobalHeader/RightContentAdmin';
import wldosFooterDom from '@/layouts/footAdmin';
import styles from '@/wldos.less';
import {
  FormOutlined,
  HomeOutlined,
  SmileOutlined,
  TableOutlined,
  UnorderedListOutlined
} from "@ant-design/icons";
import {querySiteSeo} from "@/services/user";
import {wldosHeader} from "@/utils/utils";

const iconMap = {
  home: <HomeOutlined/>,
  smile: <SmileOutlined/>,
  form: <FormOutlined/>,
  list: <UnorderedListOutlined/>,
  table: <TableOutlined/>,
};
const AdminLayout = (props) => {
  const {
    dispatch,
    children,
    location = {
      pathname: '/',
    },
    menuData,
    settings,
    loading,
  } = props;

  const [site, setSite] = useState({title: '', keywords: '', description: '', logo: '', favicon: '', version: ''});
  const [collapsed, setCollapsed] = useState(false);

  /**
   * 因为权限已经在后端过滤，返回的都是有权限菜单，不必检查权限。
   */
  const menuHandle = (menus) =>
    menus.map((item) => ({
        ...item,
        icon: item.icon && iconMap[item.icon],
        children: item.children && menuHandle(item.children),
    }));


  const menuDataRef = useRef([]);
  // 用户刚打开网站，应该是游客，触发请求，后台判断header中的token
  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'user/fetchCurrent',
      });
      dispatch({
        type: 'user/fetchAdminMenu',
      });
    }
  }, []);

  useEffect(async () => { // 获取域信息
    const res =  await querySiteSeo();

    if (res && res.data) {
      const {siteTitle, siteDescription, siteLogo, favicon, version} = res.data;

      setSite({title: `${siteTitle}_${siteDescription}`, logo: siteLogo, favicon, version});
    }
  }, []);

  const handleMenuCollapse = (payload) => {
    setCollapsed(payload);
  };

  const {formatMessage} = useIntl();
  return (
    <>
      {wldosHeader(site)}
      <ProLayout
        className={styles.slideNavWldos}
        logo={site.logo}
        title={site.title || ''}
        formatMessage={formatMessage}
        menuDataRender={(md) => menuHandle(md && md.length>0 ? menuData.pushAll(md) : menuData)}
        {...settings}
        menu={{loading, locale: false, defaultOpenAll: true, ignoreFlatMenu: true}}
        collapsed={collapsed}
        onCollapse={handleMenuCollapse}
        onMenuHeaderClick={() => history.push('/')}
        menuItemRender={(menuItemProps, defaultDom) => {
          if ( // 自定义菜单项的 渲染 方法
            menuItemProps.isUrl ||
            !menuItemProps.path ||
            location.pathname === menuItemProps.path
          ) {
            return defaultDom;
          }

          return <Link to={menuItemProps.path}>{defaultDom}</Link>;
        }}
        breadcrumbRender={(routers = []) => [
          { // 自定义面包屑的数据
            path: '/',
            breadcrumbName: formatMessage({
              id: 'menu.home',
            }),
          },
          ...routers,
        ]}
        /* eslint-disable-next-line no-unused-vars */
        itemRender={(route, params, routes, paths) => {
          const last = routes.indexOf(route) === routes.length - 1;
          return last ? (
            <span>{route.breadcrumbName}</span>
          ) : (
            <Link to={route.path}>{route.breadcrumbName}</Link>
          );
        }}
        menuHeaderRender={(lgo/* , title */) => {
          if (!site.logo) { return ''; }
          return lgo;
        }}
        // pageTitleRender={(props) => { console.log('pageTitleRender>>>', props); return 'wldos'; }}
        footerRender={() => wldosFooterDom(site.version)}
        rightContentRender={() => <RightContent/>}
        postMenuData={(menu) => { // 在显示前对菜单数据进行查看，修改不会触发重新渲染
          menuDataRef.current = menu || [];
          return menu || [];
        }}
      >
        {children}
      </ProLayout>
      <BackTop/>
    </>
  );
};

export default connect(({settings, user, loading}) => ({
  menuData: user.adminMenu,
  loading: loading.models.user,
  settings: {
    ...settings,
    layout: "side",
    contentWidth: "Fluid",
    headerHeight: 48,
  }
}))(AdminLayout);
